package org

import (
    "time"
	//"fmt"
	"math/rand"
	//"strings"
	"strconv"
	"dhfshop/service/sms"
	"dhfshop/models/org"
	"dhfshop/controllers/base"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type IdentCodeController struct {
	base.BaseController
}
// @Title 手机短信获取密码
func (this *IdentCodeController) FindPassword() {
	v := struct {
	    Mobile     string  `form:"mobile" valid:"Mobile"`
	}{} 
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return
	}
	//产生6位随机数
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	code := strconv.FormatInt(r.Int63(), 10)[0:6]
	_, err := sms.SendSMS(v.Mobile, code)
	if err == nil {
		expires := 30 * time.Minute
		validateCode, _ := strconv.ParseInt(code, 10, 64)
		mobile, _ := strconv.ParseInt(v.Mobile, 10, 64)
		identCode := &org.IdentCode{Code: validateCode, Mobile: mobile, ExpiresAt: time.Now().Add(expires).Local(), Actived: false}
		org.CreateIdentCode(identCode)
		this.Data["json"] = nil
	}
	this.ServeJSON()
}

// @Title 检测验证码是否有效
func (this *IdentCodeController) ValidateCode() {
	tel := this.GetString("tel")
	code := this.GetString("code")
	isok := org.CheckIdentCode(tel, code)
	if !isok {
		this.ServeError("验证码无效或已经过期!")
	} else {
		this.Data["json"] = nil
	}
	this.ServeJSON()
}


